package com.zf.zffencheng.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.bouncycastle.util.encoders.Base64;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;

/**
 * ClassName: JwtUtil <br/>
 * Description:  <br/>
 * date: 2021/5/8 17:20<br/>
 *
 * @author william <br/>
 */
public class JwtUtil {
    public static final String JWT_SECERT = Base64.toBase64String("geenwin2015!".getBytes());
    public static String admin_subject = "{\"adminId\": %d, \"adminType\": %d}";

    public static void main(String[] args) {
        String jwt = createJwt("1", "{\"name\":\"123\"}", 0L);
        System.out.println("jwt:"+ jwt);
        String s = validateJwt(jwt);
        System.out.println("s:"+ s);
    }
    /**
     * 签发JWT
     *
     * @param id
     * @param subject   可以是JSON数据 尽可能少
     * @param ttlMillis
     * @return String
     *
     */
    public static String createJwt(String id, String subject, long ttlMillis) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        SecretKey secretKey = generalKey();
        JwtBuilder builder = Jwts.builder().setId(id)
                // 主题
                .setSubject(subject)
                // 签发者
                .setIssuer("william")
                // 签发时间
                .setIssuedAt(now)
                // 签名算法以及密匙
                .signWith(signatureAlgorithm, secretKey);
        if (ttlMillis > 0) {
            // 过期时间
            long expMillis = nowMillis + ttlMillis;
            Date expDate = new Date(expMillis);
            builder.setExpiration(expDate);
        }
        return builder.compact();
    }

    /**
     * 验证JWT
     *
     * @param jwtStr
     * @return
     */
    public static String validateJwt(String jwtStr) {
        Claims claims = parseJwt(jwtStr);

        return claims.getSubject();
    }

    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.decode(JWT_SECERT);
        return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
    }

    /**
     *
     * 解析JWT字符串
     *
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJwt(String jwt)  {
        SecretKey secretKey = generalKey();
        return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody();
    }
}
